#encoding=utf8
'''
Created on Jun 9, 2015

@author: jingyang <jingyang@smalltreemedia.com>
'''
from app_info.models import App, AppVersion, Studio, UserGroup
from utils import JsonResponse, str_is_date
from sub_info.models import SubInfo, SUBMISSION_STATUS, ReviewStatus
from django.views.decorators.csrf import csrf_exempt
import itertools
from threads import RegisterAPMThread


@csrf_exempt
def update_app_key(req):
    '''
    get app apple_id (for iOS) or public_key (for GP) from Publish System
    '''
    prd_id = req.POST.get('product_id')
    prj_code = req.POST.get('app_code')
    apple_id = req.POST.get('apple_id')
    pub_key = req.POST.get('public_key')
    if not prd_id or not prj_code:
        return JsonResponse({'msg': 'need product_id and app_code', 'code': 0})
    if not apple_id and not pub_key:
        return JsonResponse({'msg': 'need apple_id or public_key', 'code': 0})
    try:
        app = App.objects.get(prd_id=prd_id, prj_code=prj_code)
        app.app_id = apple_id or ''
        app.pub_key = pub_key or ''
        if not app.store_link:
            if app.app_store == 'iTunes App Store':
                app.store_link = 'https://itunes.apple.com/app/id%s?mt=8' % apple_id
            elif app.app_store == 'Google Play':
                app.store_link = 'https://play.google.com/store/apps/details?id=%s' %\
                app.get_full_bundle_id()
            elif app.app_store == 'Amazon App Store':
                app.store_link = 'http://www.amazon.com/gp/mas/dl/android?p=%s' %\
                app.get_full_bundle_id()
        app.save()
        return JsonResponse({'msg': 'success', 'code': 1})
    except Exception:
        return JsonResponse({'msg': 'invalid parameters', 'code': 0})


@csrf_exempt
def update_submission_status(req):
    '''
    update submission requests' submission status from Publish System
    '''
    request_id = req.POST.get('request_id')
    status = req.POST.get('status')
    submitted_date = req.POST.get('submitted_date')
    submitted_person = req.POST.get('submitted_person', '')
    try:
        sub = SubInfo.objects.get(request_id=request_id)
    except Exception, e:
        print e
        return JsonResponse({'msg': 'invalid request_id', 'code': 0})
    if not status in [s[0] for s in SUBMISSION_STATUS]:
        return JsonResponse({'msg': 'invalid status', 'code': 0})
    if status == 'S' and not submitted_date:
        return JsonResponse({'msg': 'need submitted_date if status is submitted'})
    if status == 'S' and not submitted_person:
        return JsonResponse({'msg': 'need submitted_person if status is submitted'})
    if submitted_date and not str_is_date(submitted_date):
        return JsonResponse({'msg': 'invalid submitted_date, date format: YYYY-MM-DD'})
    sub.status = status
    sub.app_submit_date = submitted_date
    sub.sub_person = submitted_person
    sub.save()

    if status == 'S':
        # mark version log status submitted when sub info submitted
        AppVersion.objects.filter(app=sub.app, code=sub.version,
            status__in='IO').update(status='S', date_submitted=sub.app_submit_date)
#        if sub.app.app_store == 'Google Play':
#            AppVersion.objects.filter(app=sub.app, code=sub.version,
#                status__in=['I', 'O']).update(status='L',
#                    date_submitted=sub.app_submit_date,
#                    date_released=sub.app_submit_date)
#            sub.review_status = 'C'
#            sub.save()
#        else:
#            AppVersion.objects.filter(app=sub.app, code=sub.version,
#                status__in=['I', 'O']).update(status='S', date_submitted=sub.app_submit_date)
        # create a review status obj when sub info submitted
        # review status moved to PS
#        ds = 'PR'
#        ad = None
#        rd = None
#        if sub.app.app_store == 'Google Play':
#            ds = 'RE'
#            ad = sub.app_submit_date
#            rd = sub.app_submit_date
#        ReviewStatus.objects.get_or_create(sub_info=sub,
#            defaults={'status': ds, 'store_accept_date': ad,
#                      'release_date': rd})
    elif status == 'O':
        AppVersion.objects.filter(app=sub.app, code=sub.version, status='I').update(status='O')
    if sub.app_submit_date:
        AppVersion.objects.filter(app=sub.app, code=sub.version).update(\
            date_submitted=sub.app_submit_date)  # update the submitted date in AppVersion obj.
    return JsonResponse({'msg': 'success', 'code': 1})


@csrf_exempt
def update_studio_general_info(req):
    '''
    update studios' general information from Publish Service
    '''
    data = req.POST.dict()
    studio_code = data.get('studio_code')
    if not studio_code or not studio_code.isdigit():
        return JsonResponse({'msg': 'invalid studio_code', 'code': 0})
    studios = Studio.objects.filter(studio_code=studio_code)
    if not studios:
        studio = Studio(**data)
        studio.save()
    else:
        studios.update(**data)
    return JsonResponse({'msg': 'success', 'code': 1})


def get_division_teams(req):
    '''
    return all division & teams
    '''
    divisions = [{'name': d.name, 'teams': [t.name for t in d.productionteam_set.all()]}\
                 for d in UserGroup.objects.all()]
    return JsonResponse({'msg': 'success', 'code': 1, 'divisions': divisions})


def get_all_live_version(req):
    results = []
    app_list = list(set(AppVersion.objects.filter(status='L')\
        .order_by('app').values_list('app_id', flat=True)))
    app_list = App.objects.filter(id__in=app_list, status='V').exclude(prj_code='PARTY2059G') # same flurry key
    for app in app_list:
        ctx = {'product_id': app.prd_id, 'app_code': app.prj_code,
               'alt_app_code': app.old_prj_code, 'app_name': app.app_name,
               'pub_app_name': app.pub_name, 'bundle_id_prefix': app.bundle_id_prefix,
               'bundle_id_suffix': app.bundle_id_suffix,
               'full_bundle_id': app.get_full_bundle_id(),
               'platform': app.get_platform_display(), 'app_store': app.app_store,
               'apple_id': app.app_id, 'store_link': app.store_link,
               'publish_studio': '%s - %s' % (app.studio.custom_id, app.studio.pub_name),
               'studio_cloud': app.studio.cloud.cloud_id if app.studio.cloud else '',
               'initial_release_date': app.get_initial_release_date(),
               'flurry_key': app.flurry_key, 'division': app.get_division(),
               'team': app.get_team()}
        versions = [{'task_id': v.log_id,
                     'coordinator': v.get_coordinator(),
                     'version_num': v.code,
                     'release_date': v.date_released or "",
                     'release_notes': v.change_list,
                     'has_iap': True if v.iap_required == 'Y' else False,
                     'has_ads': True if v.ads_required == 'Y' else False,
                     'has_cross_promo': True if v.cross_promo_required == 'Y' else False}\
                    for v in app.appversion_set.filter(status='L')]
        ctx.update({'versions': versions})
        results.append(ctx)
    return JsonResponse({'msg': 'success', 'code': 1, 'results': results,
        'count': app_list.count()})


@csrf_exempt
def update_review_status(req):
    review_status = req.POST.get('status')
    if not review_status in ['rejected', 'released']:
        return JsonResponse({'msg': "invalid status, must be 'rejected' or 'released'",
                             'code': 0})
    release_date = req.POST.get('release_date')
    if release_date and not str_is_date(release_date):
        return JsonResponse({'msg': "invalid release_date, date format: YYYY-MM-DD",
                             'code': 0})
    if review_status == 'released' and not release_date:
        return JsonResponse({'msg': "need release_date if status is released",
                             'code': 0})
    request_id = req.POST.get('request_id')
    try:
        sub_info = SubInfo.objects.get(request_id=request_id)
    except SubInfo.DoesNotExist:
        return JsonResponse({'msg': "invalid request_id, not found", 'code': 0})
    sub_info.review_status = 'A' if review_status == 'rejected' else 'C'
    sub_info.save()
    v = sub_info.app.appversion_set.filter(code=sub_info.version,
                                           status__in=['S', 'L'])[:1]
    if v:
        if sub_info.review_status == 'C':
            v[0].status = 'L'
            v[0].date_released = release_date
            v[0].save()
            # since APM is not live, do not call its API in prod env
            #RegisterAPMThread(sub_info).start()
    return JsonResponse({'msg': "success", 'code': 1})
